<template>
  <div :key="Math.random()" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts' // echarts theme
import { debounce } from '@/utils'

require('echarts/theme/macarons')

export default {
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    chartData: {
      type: Object,
      required: true
    }
    // predictedTrend: {
    //   type: String,
    //   required: true // 'up' or 'down'
    // }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
        this.initChart()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ name, data }) {
      const data1 = {
        'counties': JSON.parse(JSON.stringify(data.counties)),
        'timeline': JSON.parse(JSON.stringify(data.timeline)),
        'series': JSON.parse(JSON.stringify(data.series))
      }
      data1.series.forEach(function(item) {
        item.sort((a, b) => b[2] - a[2])
        item.forEach(function(subItem, index) {
          subItem.push(index)
        })
      })
      var itemStyle = {
        opacity: 0.8
      }
      var sizeFunction = function(x, index) {
        var y = Math.sqrt(x / 5e8) + 0.1
        return y * (index > 9 ? 120 : 260)
      }
      // Schema:
      var schema = [
        { name: 'Income', index: 0, text: 'GDP', unit: '万亿' },
        { name: 'LifeExpectancy', index: 1, text: '人才外流风险指数', unit: '' },
        { name: 'Population', index: 2, text: '经济发展不平衡指数', unit: '' },
        { name: 'Country', index: 3, text: '国家', unit: '' }
      ]
      var option = {
        baseOption: {
          timeline: {
            axisType: 'category',
            orient: 'vertical',
            autoPlay: true,
            inverse: true,
            playInterval: 3000,
            left: null,
            right: 0,
            top: 20,
            bottom: 20,
            width: 55,
            height: null,
            symbol: 'none',
            itemStyle: {
              color: '#fff'
            },
            label: {
              color: 'rgba(54, 196, 255, 0.7)'
            },
            checkpointStyle: {
              borderWidth: 2,
              borderColor: 'rgba(54, 196, 255, 0.7)',
              color: 'rgba(54, 196, 255, 0.7)'
            },
            controlStyle: {
              showNextBtn: false,
              showPrevBtn: false,
              backgroundColor: '#fff'
            },
            emphasis: {
              label: {
                color: 'rgba(54, 196, 255, 0.7)'
              },
              controlStyle: {
                showNextBtn: false,
                showPrevBtn: false,
                color: 'rgba(54, 196, 255, 0.7)',
                backgroundColor: '#fff'
              }
            },
            data: []
          },
          title: [
            {
              text: data1.timeline[0],
              textAlign: 'center',
              left: '130',
              top: '15',
              textStyle: {
                color: 'rgba(54, 196, 255, 0.7)',
                fontSize: 44
              }
            }
          ], //
          tooltip: {
            padding: 5,
            borderWidth: 1,
            formatter: function(obj) {
              var value = obj.value
              // prettier-ignore
              return schema[3].text + '：' + value[3] + '<br>' +
                schema[1].text + '：' + value[1] + schema[1].unit + '<br>' +
                schema[0].text + '：' + value[0] + schema[0].unit + '<br>' +
                schema[2].text + '：' + value[2] + '<br>'
            }
          },
          grid: {
            top: '10%',
            left: '6%',
            right: '5%',
            bottom: '8%',
            containLabel: true
          },
          xAxis: {
            type: 'log',
            name: '',
            nameGap: 25,
            nameLocation: 'middle',
            nameTextStyle: {
              fontSize: 18
            },
            splitLine: {
              show: false
            },
            axisLine: { // 坐标轴轴线相关设置。数学上的x轴
              show: true,
              lineStyle: {
                color: 'rgba(0, 211, 255, 0.1)'
              }
            },
            axisLabel: { // 坐标轴刻度标签的相关设置
              textStyle: {
                color: 'rgba(54, 196, 255, 0.7)',
                margin: 15
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            name: 'GDP(亿美元)',
            nameTextStyle: {
              color: 'rgba(54, 196, 255, 0.7)',
              fontSize: 12,
              padding: [0, 0, 0, -50]
            },
            type: 'value',
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(0, 154, 255, 0.2)'
              }
            },
            axisLine: {
              show: false
            },
            splitArea: { show: false },
            axisLabel: {
              margin: 20,
              textStyle: {
                color: 'rgba(54, 196, 255, 0.7)'
              }
            },
            axisTick: {
              show: true,
              lineStyle: {
                color: 'rgba(0, 154, 255, 0.4)'
              }
            }
          },
          visualMap: [
            {
              show: false,
              dimension: 3,
              categories: data1.series[0].map((item) => item[3]),
              inRange: {
                color: (function() {
                  var colors = ['#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba']
                  let fillColors = []
                  if (data1.counties.length > colors.length) {
                    fillColors = Array.from({ length: data1.counties.length - colors.length }, () => '#999')
                  }
                  return colors.concat(fillColors)
                })()
              }
            }
          ],
          series: [
            {
              type: 'scatter',
              itemStyle: itemStyle,
              data: data1.series[0],
              symbolSize: function(val) {
                return sizeFunction(val[2], val[5])
              }
            }
          ],
          animationDurationUpdate: 1500,
          animationEasingUpdate: 'quinticInOut'
        },
        options: []
      }
      for (var n = 0; n < data1.timeline.length; n++) {
        option.baseOption.timeline.data.push(data1.timeline[n])
        option.options.push({
          title: {
            show: true,
            text: data1.timeline[n] + ''
          },
          visualMap: [
            {
              show: false,
              dimension: 3,
              categories: data1.series[n].map((item) => item[3]),
              inRange: {
                color: (function() {
                  var colors = ['#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba']
                  let fillColors = []
                  if (data1.counties.length > colors.length) {
                    fillColors = Array.from({ length: data1.counties.length - colors.length }, () => '#ccc')
                  }
                  return colors.concat(fillColors)
                })()
              }
            }
          ],
          series: {
            name: data1.timeline[n],
            type: 'scatter',
            itemStyle: itemStyle,
            data: data1.series[n],
            symbolSize: function(val) {
              return sizeFunction(val[2], val[5])
            }
          }
        })
      }
      this.chart.setOption(option, true)
    }
  }
}
</script>
